package org.springblade.tms.module.demandorder.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.tms.global.enums.*;
import org.springblade.tms.module.demandextrainfo.entity.TmDemandExtraInfo;
import org.springblade.tms.module.demandextrainfo.service.ITmDemandExtraInfoService;
import org.springblade.tms.module.demandextrainfo.vo.TmDemandExtraInfoVO;
import org.springblade.tms.module.demandextrainfo.wrapper.TmDemandExtraInfoWrapper;
import org.springblade.tms.module.demandorder.dto.AppDemandOrderDto;
import org.springblade.tms.module.demandorder.dto.RejectOrderDto;
import org.springblade.tms.module.demandorder.entity.TMDemandOrder;
import org.springblade.tms.module.demandorder.service.IDemandOrderService;
import org.springblade.tms.module.demandorder.vo.TMDemandOrderVO;
import org.springblade.tms.module.demandorder.wrapper.DemandOrderWrapper;
import org.springblade.tms.module.demandorderitem.entity.TMDemandOrderItem;
import org.springblade.tms.module.demandorderitem.service.IDemandOrderItemService;
import org.springblade.tms.module.station.entity.TMStation;
import org.springblade.tms.module.station.service.IStationService;
import org.springblade.tms.module.userinfo.base.DriverManagementService;
import org.springblade.tms.module.userinfo.entity.TMUserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @projectName: BladeX
 * @package: org.springblade.tms.module.demandorder.base
 * @className: AppDemandListService
 * @author: yr
 * @description: app需求单服务
 * @date: 2022/3/21 10:57
 */
@Service
@Transactional
public class AppDemandListService {
	@Resource
	private IDemandOrderService demandOrderService;
	@Resource
	private IDemandOrderItemService demandOrderItemService;
	@Resource
	private DriverManagementService driverManagementService;
	@Resource
	private ITmDemandExtraInfoService tmDemandExtraInfoService;
	@Resource
	private IStationService stationService;

	/**
	 * @param rejectOrderDto:
	 * @return void
	 * @author yr
	 * @description 接单或拒单
	 * @date 2022/3/21 11:27
	 */
	public R rejectOrder(RejectOrderDto rejectOrderDto) {
		TMDemandOrder demandOrder = demandOrderService.getOne(Condition.getQueryWrapper(new TMDemandOrder())
			.lambda().eq(TMDemandOrder::getId, rejectOrderDto.getId()));
		if (rejectOrderDto.getType().equals(DemandOperationalEnum.ORDERS.getDescription())) {
			demandOrder.setDemandStatus(DemandStatusEnum.ALREADY.value());
		} else if (rejectOrderDto.getType().equals(DemandOperationalEnum.REFUSAL.getDescription())) {
			demandOrder.setDemandStatus(DemandStatusEnum.REJECTED.value());
		}
		boolean updateById = demandOrderService.updateById(demandOrder);
		return R.status(updateById);
	}

	/**
	 * @param appDemandOrderDto:
	 * @param query:
	 * @return R<IPage < TMDemandOrderVO>>
	 * @author yr
	 * @description 查询
	 * @date 2022/3/21 14:14
	 */
	public R<IPage<TMDemandOrderVO>> list(AppDemandOrderDto appDemandOrderDto, Query query) {
		TMUserInfo tmUserInfo = driverManagementService.getTmUserInfo();
		LambdaQueryWrapper<TMDemandOrder> queryWrapper = Condition.getQueryWrapper(new TMDemandOrder()).lambda()
			.eq(appDemandOrderDto.getDemandStatus() != null, TMDemandOrder::getDemandStatus, appDemandOrderDto.getDemandStatus())
			.like(appDemandOrderDto.getOrderNo() != null, TMDemandOrder::getOrderNo, appDemandOrderDto.getOrderNo());
		if (tmUserInfo != null && tmUserInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue())) {
			queryWrapper = queryWrapper.eq(TMDemandOrder::getCarrierNo, tmUserInfo.getTmId());
		}
		IPage<TMDemandOrder> page = demandOrderService.page(Condition.getPage(query), queryWrapper.orderByDesc(TMDemandOrder::getCreateTime, TMDemandOrder::getId));
		IPage<TMDemandOrderVO> tmDemandOrderVOIPage = DemandOrderWrapper.build().pageVO(page);
		List<Long> ids = page.getRecords().stream().map(TMDemandOrder::getId).collect(Collectors.toList());
		List<TMDemandOrderItem> tmDemandOrderItems = demandOrderItemService.lambdaQuery()
			.in(!ids.isEmpty(), TMDemandOrderItem::getParentId, ids).apply(ids.isEmpty(), "1=2").list();
		Map<Long, List<TMDemandOrderItem>> transportMap = tmDemandOrderItems.stream().collect(Collectors.groupingBy(TMDemandOrderItem::getParentId));
		//封装物料信息和原位置信息
		for (TMDemandOrderVO record : tmDemandOrderVOIPage.getRecords()) {
			record.setIsItPossibleToAssignAWaybill(!transportMap.getOrDefault(record.getId(), new ArrayList<>()).stream().allMatch(item -> BigDecimal.ZERO.compareTo(item.getNum()) == 0));
			record.setSourceLocationStreet(new StringBuilder(record.getStartLocationArea())
				.append(record.getStartLocationCity()).append(record.getStartLocationStreet()).toString());
			record.setDestinationStreet(new StringBuilder(record.getTargetLocationArea())
				.append(record.getTargetLocationCity()).append(record.getTargetLocationStreet()).toString());
			transportMap.get(record.getId()).forEach(item -> {
				record.setMaterialInformation(new StringBuilder(record.getMaterialInformation()).append(item.getMatDesc())
					.append("*").append(item.getNum().toString()).append("(")
					.append(item.getUnit()).append(")").toString());
			});
		}
		return R.data(tmDemandOrderVOIPage);
	}

	//补充信息详情
	public R<TmDemandExtraInfo> detail(Long demandId) {
		TmDemandExtraInfo result = tmDemandExtraInfoService.getOne(TmDemandExtraInfo.buildWrapper(1, TmDemandExtraInfo.builder().parentId(demandId).build()));
		TmDemandExtraInfoVO tmDemandExtraInfoVO = TmDemandExtraInfoWrapper.build().entityVO(result);
		if (tmDemandExtraInfoVO == null) {
			R<TmDemandExtraInfo> objectR = new R<>();
			objectR.setCode(200);
			objectR.setSuccess(true);
			objectR.setData(TmDemandExtraInfo.builder().build());
			return objectR;
		}
		if (result.getTransportType().equals(TransportTypeEnum.OCEAN_SHIPPING.getValue())) {
			tmDemandExtraInfoVO.setSendLocationTxt(stationService.lambdaQuery()
				.eq(TMStation::getCode, tmDemandExtraInfoVO.getSendLocation())
				.eq(TMStation::getType, StationTypeEnum.port.getValue())
				.one().getDescribe());
			tmDemandExtraInfoVO.setTargetLocationTxt(stationService.lambdaQuery()
				.eq(TMStation::getCode, tmDemandExtraInfoVO.getTargetLocation())
				.eq(TMStation::getType, StationTypeEnum.port.getValue())
				.one().getDescribe());
		} else {
			tmDemandExtraInfoVO.setTrainSendLocationTxt(stationService.lambdaQuery()
				.eq(TMStation::getCode, tmDemandExtraInfoVO.getTrainSendLocation())
				.eq(TMStation::getType, StationTypeEnum.port.getValue())
				.one().getDescribe());
			tmDemandExtraInfoVO.setTrainTargetLocationTxt(stationService.lambdaQuery()
				.eq(TMStation::getCode, tmDemandExtraInfoVO.getTrainTargetLocation())
				.eq(TMStation::getType, StationTypeEnum.port.getValue())
				.one().getDescribe());
		}
		return R.data(tmDemandExtraInfoVO);
	}
}
